// dh-services 云对象 - 医疗服务管理
const db = uniCloud.database();
const _ = db.command;
const { autoMountHospitalId, softDelete, batchSoftDelete } = require('dh-common');

/**
 * 统一响应格式化辅助函数
 */
function formatResponse(code, data = null, message = 'success', extraFields = {}) {
	return {
		code,
		data,
		message,
		success: (code === 200 || code === 201),
		timestamp: Date.now(),
		...extraFields
	};
}

/**
 * 统一错误响应辅助函数
 */
function formatError(error, defaultMessage = '操作失败') {
	console.error('[dh-services] 错误:', error);
	return {
		code: 500,
		message: error.message || defaultMessage,
		success: false,
		timestamp: Date.now()
	};
}

module.exports = {
	/**
	 * 请求前拦截
	 */
	async _before(methodName, params) {
		const uniIdToken = this.getUniIdToken();
		console.log(`[dh-services] 调用方法: ${methodName}, 用户ID: ${uniIdToken?.uid}`);

		const writeMethods = ['create', 'update', 'delete', 'batch'];
		if (methodName && writeMethods.some(method => methodName.toLowerCase().includes(method))) {
			if (!uniIdToken || !uniIdToken.uid) {
				throw new Error('401|未授权的访问');
			}
		}

		if (params && typeof params === 'object') {
			for (let key in params) {
				if (typeof params[key] === 'string') {
					params[key] = params[key].trim();
				}
			}
		}
	},

	async getServiceById(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '服务ID不能为空');
			}

			const res = await db.collection('dh-services').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '服务不存在');
			}
			return formatResponse(200, res.data[0]);
		} catch (error) {
			return formatError(error, '获取服务失败');
		}
	},

	async listServices(query = {}, skip = 0, limit = 20) {
		try {
			if (typeof query !== 'object' || query === null || Array.isArray(query)) {
				query = {};
			}
			skip = parseInt(skip) || 0;
			limit = parseInt(limit) || 20;
			
			const res = await db.collection('dh-services')
				.where(query)
				.skip(skip)
				.limit(limit)
				.get();
			return formatResponse(200, res.data, 'success', { count: res.data.length });
		} catch (error) {
			return formatError(error, '获取服务列表失败');
		}
	},

	async createService(data) {
		try {
			if (!data.service_name) {
				return formatResponse(400, null, '服务名称不能为空');
			}

			let serviceData = {
				service_name: data.service_name,
				service_type: data.service_type || '',
				description: data.description || '',
				price: data.price || 0,
				unit: data.unit || '次',
				duration: data.duration || 30,
				category: data.category || '',
				equipment_required: data.equipment_required || [],
				staff_required: data.staff_required || [],
				is_active: data.is_active !== undefined ? data.is_active : true,
				is_deleted: false,  // 软删除字段，默认未删除
				create_time: Date.now(),
				update_time: Date.now()
			};

			// 🏥 自动挂载医院ID（单一医院系统特性）
			serviceData = await autoMountHospitalId(serviceData);

			const res = await db.collection('dh-services').add(serviceData);
			return formatResponse(201, { _id: res.id }, '服务创建成功');
		} catch (error) {
			return formatError(error, '创建服务失败');
		}
	},

	async updateService(id, data) {
		try {
			if (!id) {
				return formatResponse(400, null, '服务ID不能为空');
			}

			const updateData = {
				...data,
				update_time: Date.now()
			};

			await db.collection('dh-services').doc(id).update(updateData);
			return formatResponse(200, null, '服务信息更新成功');
		} catch (error) {
			return formatError(error, '更新服务失败');
		}
	},

	async deleteService(id, reason = '') {
		try {
			if (!id) {
				return formatResponse(400, null, '服务ID不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await softDelete('dh-services', id, uniIdToken?.uid || '', reason);
			
			if (result.code === 200) {
				return formatResponse(200, null, '服务已移至回收站');
			} else {
				return formatResponse(result.code, null, result.message);
			}
		} catch (error) {
			return formatError(error, '删除服务失败');
		}
	},

	async batchUpdateServices(updates) {
		try {
			if (!Array.isArray(updates) || updates.length === 0) {
				return formatResponse(400, null, '更新数据不能为空');
			}

			const promises = updates.map(item =>
				db.collection('dh-services').doc(item._id).update({
					...item,
					update_time: Date.now()
				})
			);

			await Promise.all(promises);
			return formatResponse(200, null, `批量更新${updates.length}条记录成功`);
		} catch (error) {
			return formatError(error, '批量更新失败');
		}
	},

	async batchDeleteServices(ids, reason = '') {
		try {
			if (!Array.isArray(ids) || ids.length === 0) {
				return formatResponse(400, null, 'ID列表不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await batchSoftDelete('dh-services', ids, uniIdToken?.uid || '', reason);
			
			return formatResponse(result.code, result.data, result.message);
		} catch (error) {
			return formatError(error, '批量删除失败');
		}
	},

	async getServicesByType(serviceType, hospitalId = null, skip = 0, limit = 20) {
		try {
			let query = { service_type: serviceType, is_active: true };
			if (hospitalId) {
				query.hospital_id = hospitalId;
			}

			const res = await db.collection('dh-services')
				.where(query)
				.skip(skip)
				.limit(limit)
				.get();

			return formatResponse(200, res.data, 'success', { count: res.data.length });
		} catch (error) {
			return formatError(error, '获取服务失败');
		}
	},

	async updateServiceStatus(id, status) {
		try {
			if (!id) {
				return formatResponse(400, null, '服务ID不能为空');
			}

			await db.collection('dh-services').doc(id).update({
				is_active: status,
				update_time: Date.now()
			});

			return formatResponse(200, null, '服务状态更新成功');
		} catch (error) {
			return formatError(error, '更新服务状态失败');
		}
	},

	/**
	 * 获取服务信息（包含价格计算）
	 * @param {string} id - 服务ID
	 * @param {number} quantity - 数量，默认为1
	 */
	async getServiceWithPrice(id, quantity = 1) {
		try {
			if (!id) {
				return formatResponse(400, null, '服务ID不能为空');
			}

			// 获取服务基本信息
			const res = await db.collection('dh-services').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '服务不存在');
			}
			
			const service = res.data[0];
			
			// 调用价格计算服务
			const pricingModule = uniCloud.importObject('dh-pricing');
			const priceResult = await pricingModule.calculatePrice(1, id, quantity);
			
			// 合并服务信息和价格信息
			const result = {
				...service,
				priceInfo: priceResult.data
			};
			
			return formatResponse(200, result);
		} catch (error) {
			return formatError(error, '获取服务信息失败');
		}
	},

	/**
	 * 获取服务列表（包含价格计算）
	 * @param {object} query - 查询条件
	 * @param {number} skip - 跳过数量
	 * @param {number} limit - 限制数量
	 */
	async listServicesWithPrices(query = {}, skip = 0, limit = 20) {
		try {
			if (typeof query !== 'object' || query === null || Array.isArray(query)) {
				query = {};
			}
			skip = parseInt(skip) || 0;
			limit = parseInt(limit) || 20;
			
			const res = await db.collection('dh-services')
				.where(query)
				.skip(skip)
				.limit(limit)
				.get();
			
			// 为每个服务计算价格
			const pricingModule = uniCloud.importObject('dh-pricing');
			const servicesWithPrices = await Promise.all(
				res.data.map(async (service) => {
					try {
						const priceResult = await pricingModule.calculatePrice(1, service._id, 1);
						return {
							...service,
							priceInfo: priceResult.data
						};
					} catch (error) {
						console.error(`计算服务${service._id}价格失败:`, error);
						return {
							...service,
							priceInfo: {
								basePrice: service.base_price || 0,
								finalPrice: service.base_price || 0,
								discount: 0,
								savingAmount: 0,
								promotionInfo: null
							}
						};
					}
				})
			);
			
			return formatResponse(200, servicesWithPrices, 'success', { count: servicesWithPrices.length });
		} catch (error) {
			return formatError(error, '获取服务列表失败');
		}
	}
};
